<template>
  <div class="container">
    <el-row>
      <SearchForm
        :form-data="selectFormData"
        :family-list="familyList"
        :tag-list="tagList"
        :member-list="memberList"
        :loading="loading"
        :source-types="sourceTypes"
        :income-expense-types="incomeExpenseTypes"
        @search="searchDetails"
        @reset="reset"
        @get-members="getMembers"
        @get-tags="getTags"
        @update:form-data="handleFormDataChange"
      />
    </el-row>

    <!-- 数据表格区域 -->
    <DetailTable
      :data="DetailList"
      :current-family-id="selectFormData.familyId!"
      :family-list="familyList"
      :tag-list="tagList"
      :source-types="sourceTypes"
      :income-expense-types="incomeExpenseTypes"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      :pages="pages"
      @download="download"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="searchDetails"
    />


  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import {exportDetail, getDetailPage} from "@/api/detail";
import type {Detail, Family, FamilyMember, SelectForm, Tag} from "@/api/detail/type.ts";
import {storeToRefs} from "pinia";
import {useDetailStore} from "@/stores/useDetailStore.ts";
import SearchForm from "./SearchForm.vue";

import DetailTable from "./DetailTable.vue";
import {getAllFamily} from "@/api/family";
import {getMembersById} from "@/api/member";
import {getTagListByFamilyId} from "@/api/tag";
import {ElMessage} from "element-plus";

const detailStore = useDetailStore();
const {sourceTypes, incomeExpenseTypes} = storeToRefs(useDetailStore());


// 加载状态
const loading = ref(false);

// 家庭列表数据
const familyList = ref<Family[]>([]);

// 获取家庭数据
const getFamilies = async () => {
  try {
    const response = await getAllFamily();
    familyList.value = response.data.map(family => {
      return {
        id: family.id!,
        name: family.name!
      };
    });
  } catch (error) {
    console.error("获取家庭失败:", error);
  }
};

// 家庭成员数据列表
const memberList = ref<FamilyMember[]>([]);

//获取家庭成员
async function getMembers(family_id: number) {
  try {
    const res = await getMembersById(family_id);
    memberList.value = res.data.map(f => {
      return {
        id: f.id!,
        name: f.name!,
      }
    });
  } catch (error) {
    console.error("获取家庭成员失败:", error);
    ElMessage.error("获取家庭成员失败");
  }
}

// 标签列表数据
const tagList = ref<Tag[]>([]);

//获取家庭标签
async function getTags(family_id: number) {
  try {
    const res = await getTagListByFamilyId(family_id);
    tagList.value = res.data.map(t => {
      return {
        id: t.id,
        name: t.name
      }
    })
  } catch (error) {
    console.error("获取家庭标签失败:", error);
    ElMessage.error("获取家庭标签失败");
  }
}

const selectFormData = reactive<SelectForm>({
  familyId: null,
  tagIds: [],
  incomeExpenseType: null,
  familyMemberId: null,
  sourceType: null,
  startTime: null,
  endTime: null,
  pageNum: 1,
  pageSize: 10
});

function handleFormDataChange(newData: SelectForm) {
  selectFormData.familyId = newData.familyId;
  selectFormData.tagIds = newData.tagIds;
  selectFormData.incomeExpenseType = newData.incomeExpenseType;
  selectFormData.familyMemberId = newData.familyMemberId;
  selectFormData.sourceType = newData.sourceType;
  selectFormData.startTime = newData.startTime;
  selectFormData.endTime = newData.endTime;
}

//重置搜索内容
function reset() {
  selectFormData.familyId = null;
  selectFormData.tagIds = [];
  selectFormData.incomeExpenseType = null;
  selectFormData.familyMemberId = null;
  selectFormData.sourceType = null;
  selectFormData.startTime = null;
  selectFormData.endTime = null;
}

//详情列表数据
const DetailList = ref<Detail[]>([]);
const total = ref(0);
const pages = ref(0);

//获取列表数据
async function searchDetails() {
  try {
    const res = await getDetailPage(selectFormData);
    DetailList.value = res.data.records;
    total.value = res.data.total || 0;
    pages.value = res.data.pages;
  } catch (error) {
    console.error("获取详情列表失败:", error);
    ElMessage.error("获取详情列表失败")
  }
}

//分页组件
const currentPage = ref<number>(selectFormData.pageNum);
const pageSize = ref<number>(selectFormData.pageSize);

//page_size改变触发
function handleSizeChange(size: number) {
  selectFormData.pageSize = size;
  pageSize.value = size;
  searchDetails();
}

//current_page改变触发
function handleCurrentChange(page: number) {
  selectFormData.pageNum = page;
  currentPage.value = page;
  searchDetails();
}

/**
 * 导出数据
 */
async function download() {
  try {
    const response = await exportDetail(selectFormData);

    // 确保获取的是AxiosResponse
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] ||
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    // 生成文件名
    const familyName = selectFormData.familyId
      ? familyList.value.find(f => f.id === selectFormData.familyId)?.name || ''
      : '';
    let fileName = `${familyName}收支明细.xlsx`;

    // 从响应头解析文件名（兼容多种格式）
    const disposition = response.headers?.['content-disposition'];
    if (disposition) {
      const utf8Match = disposition.match(/filename\*=utf-8''([^;]+)/i);
      const plainMatch = disposition.match(/filename="([^"]+)"/i);

      if (utf8Match) {
        fileName = decodeURIComponent(utf8Match[1]);
      } else if (plainMatch) {
        fileName = plainMatch[1];
      }
    }

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();

    // 延迟清理
    setTimeout(() => {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 200);
  } catch (e) {
    console.error('导出失败详情:', e);
    ElMessage.error(`导出失败: ${e.message || '未知错误'}`);
  }
}

// 组件挂载时获取标签数据
onMounted(() => {
  getFamilies();
  //获取字典数据
  detailStore.fetchDictionaries();
});
</script>

<style scoped lang="scss">
.container {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  padding-right: 20px;
  display: flex;
  flex-direction: column;


}
</style>
